package com.sky.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.dto.DishDTO;
import com.sky.dto.DishPageQueryDTO;
import com.sky.entity.Category;
import com.sky.entity.Dish;
import com.sky.mapper.CategoryMapper;
import com.sky.mapper.DishMapper;
import com.sky.result.PageResult;
import com.sky.result.Result;
import com.sky.service.DishService;
import com.sky.vo.DishVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
@Service
public class DishServiceImpl implements DishService {

    @Autowired
    private DishMapper dishMapper;
    @Autowired
    private CategoryMapper categoryMapper;

    /**
     * 菜品分页查询
     *
     * @param dto
     * @return
     */
    @Override
    public Result pageDish(DishPageQueryDTO dto) {
     //非空判断
           if(dto.getPage()==null){
               dto.setPage(1);
           }
           if(dto.getPageSize()==null){
               dto.setPageSize(10);
           }

           //开启分页查询
           PageHelper.startPage(dto.getPage(),dto.getPageSize());

           //调用mapper层获取数据
        Page<Dish> dishes = dishMapper.PageDish(dto);

        //1.6关联表数据
         List<DishVO> dishVOList=new ArrayList<>();

         //1.0遍历分页查询后的10条数据
        dishes.forEach(dish -> {
            //1.1创建一个对象，用于存储所有数据，包括多对多表关联的表字段
            DishVO dishVO=new DishVO();
            //1.2将dish内1条数据克隆进dishVO内
            BeanUtils.copyProperties(dish,dishVO);
            //1.4调用关联语法，通过dish的Id，获取category表的id
            Category category = categoryMapper.getByid(dish.getCategoryId());
            //1.5通过category表id，获取category表的name，并存放进dishVO内
            dishVO.setCategoryName(category.getName());
            //1.7将dishVO的一条数据，add进dishVOList集合里，通过遍历10条数据，全部存放进去
            dishVOList.add(dishVO);

        });

        //封装数据
        PageResult pageResult =new PageResult();
           //将10条表数据存放进pageResult内
           pageResult.setRecords(dishVOList);
           //getTotal是java提供的一个方法，用来获取当前页数，存放进pageResult里
           pageResult.setTotal(dishes.getTotal());



        //返回数据
        return Result.success(pageResult);
    }

    /**
     * 根据id查询菜品
     *
     * @param dishPageQueryDTO
     * @return
     */
    @Override
    public Result listDish(DishPageQueryDTO dishPageQueryDTO) {
        //非空判断
        if (dishPageQueryDTO.getCategoryId()==null){
            return Result.error(MessageConstant.UNKNOWN_ERROR);
        }
        //调用mapper层
        Page<Dish> dishes = dishMapper.PageDish(dishPageQueryDTO);

        return Result.success(dishes);
    }
}
